/* components */
import { ConnectorModuleConnectorDialogDetail } from '@src/modules/connector/components'
/* hooks */
import { 
  useConnectorCardSettingFetchEditConnectorOptions, 
  useConnectorCardSettingFetchSaveConnectorOptions 
} from '@src/modules/connector/hooks'
import { useDialog } from '@hooks/useDialog'
/* model */
import { 
  AppTypeEnum,
  ConnectorDialogDefaultDetailValue, 
  ConnectorDialogDetailData, 
  ConnectorEditOptions, 
  ConnectorModuleComponentNameEnum,
  ConnectorOptionsActionEnum,
  CreateConnectorModalFields,
} from '@src/modules/connector/model'
/* scss */
import '@src/modules/connector/components/card-item/index.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, defineComponent, PropType, Ref, ref, CreateElement } from 'vue'
import { CommonComponentInstance } from '@model/VC'
/* util */
import Log from '@src/util/log'
import { 
  connectComponentValueToServerValue, 
  connectorSaveValidate, 
  connectServerValueToComponentValueForEditWithTaskToPaas,
  sortConnectorToFieldsByShowFieldNameList, 
} from '@src/modules/connector/util'
/* types */
import { ConnectorGetEditOptionsParams, ConnectorSaveOptionsParams } from '@src/modules/connector/types'
import { CardInfoConnectorInfo } from '@model/entity/CardInfo'
import { t } from '@src/locales'
import { isFalse } from '@src/util/type'

export type ConnectorModuleEditConnectorDialogProps = {
  connectorInfo: CardInfoConnectorInfo;
  fromBizTypeName: string;
}

export interface ConnectorModuleEditConnectorDialogSetupState {
  
}

export enum ConnectorModuleEditConnectorDialogEmitEventNameEnum {
  Input = 'input',
  Close = 'close',
  Finish = 'finish',
}

export type ConnectorModuleEditConnectorDialogInstance = ComponentInstance & ConnectorModuleEditConnectorDialogSetupState
export type ConnectorModuleEditConnectorDialogVM = ComponentRenderProxy<ConnectorModuleEditConnectorDialogProps> & CommonComponentInstance & ConnectorModuleEditConnectorDialogInstance

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorModuleEditConnectorDialog,
  emits: [
    ConnectorModuleEditConnectorDialogEmitEventNameEnum.Input,
    ConnectorModuleEditConnectorDialogEmitEventNameEnum.Close,
    ConnectorModuleEditConnectorDialogEmitEventNameEnum.Finish,
  ],
  props: {
    title: {
      type: String as PropType<string>,
      default: t('common.base.editModule', {module: t('common.connector.title.additionalCard')}),
    },
    visible: {
      type: Boolean as PropType<boolean>,
      default: false,
    },
    connectorInfo: {
      type: Object as PropType<CardInfoConnectorInfo>,
      default: () => ({}),
    },
    fromBizTypeName: {
      type: String as PropType<string>,
      default: ''
    }
  },
  data() {
    return {
      fields: CreateConnectorModalFields.slice(),
    }
  },
  setup(props: ConnectorModuleEditConnectorDialogProps, { emit }) {
    
    // 获取编辑连接器配置
    const {
      loading: fetchConnectorEditOptionsLoading, 
      connectorEditOptions, 
      fetchConnectorEditOptions 
    } = useConnectorCardSettingFetchEditConnectorOptions()
    
    // 保存连接器配置
    const { 
      loading: fetchSaveConnectorOptionsLoading, 
      fetchSaveConnectorOptions 
    } = useConnectorCardSettingFetchSaveConnectorOptions()
    
    const detailValue: Ref<ConnectorDialogDetailData> = ref(ConnectorDialogDefaultDetailValue)
    
    const { visible: insideVisible, showDialog, hideDialog } = useDialog()
    
    // 关闭事件
    const onDialogCloseHandler = () => {
      initConnectorDialogDefaultDetailValue()
      emit(ConnectorModuleEditConnectorDialogEmitEventNameEnum.Close)
    } 
    
    // 完成事件
    const onDialogFinishHandler = () => {
      emit(ConnectorModuleEditConnectorDialogEmitEventNameEnum.Finish)
    } 
    
    // 初始化detailValue
    const initConnectorDialogDefaultDetailValue = () => {
      detailValue.value = ConnectorDialogDefaultDetailValue
    }

    return {
      insideVisible,
      
      detailValue,
      
      fetchConnectorEditOptionsLoading,
      fetchSaveConnectorOptionsLoading,
      
      fetchConnectorEditOptions,
      fetchSaveConnectorOptions,
      
      showDialog,
      hideDialog,
      
      onDialogCloseHandler,
      onDialogFinishHandler,
      initConnectorDialogDefaultDetailValue
    }
    
  },
  computed: {
    disabled(): boolean {
      return this.fetchConnectorEditOptionsLoading || this.fetchSaveConnectorOptionsLoading
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(newValue) {
        
        if (newValue) {
          this.onVisibleShowHandler()
        } else {
          this.onVisibleHideHandler()
        }
        
      }
    }
  },
  methods: {
    /**
     * @description 取消
    */
    cancel() {
      this.hideDialog()
      this.onDialogCloseHandler()
    },
    /**
     * @description 完成
    */
    finish() {
      
      const nameFormValue: Record<string, string> = { 
        name: '', 
        description: ''
      }
      
      const bizTypeId: string = this.detailValue.bizTypeId
      
      const validated = connectorSaveValidate(this.detailValue)
      
      if (isFalse(validated)) {
        
        Log.warn('validate fail', connectorSaveValidate.name)
        
        return
        
      }
      
      const params: ConnectorSaveOptionsParams = connectComponentValueToServerValue(
        nameFormValue,
        this.detailValue,
        bizTypeId,
        this.connectorInfo.fromBizType,
        this.connectorInfo.toBizType,
      )
      
      Log.info(params, 'params')
      
      this.fetchSaveConnectorOptionsImpl(params)
      
    },
    /** 
     * @description 获取 连接器配置
    */
    fetchConnectorOptionsImpl() {
      
      const params: ConnectorGetEditOptionsParams = this.connectorInfo as ConnectorGetEditOptionsParams
      
      this.fetchConnectorEditOptions(params).then((result) => {
        
        // 找到是否存在showFieldNameList并且能找到选中actionSelectItem进行字段排序
        const showFieldNameList = result?.showFieldNameList || []
        const actionSelectItem = result?.actionList.find(item=> item.action === ConnectorOptionsActionEnum.Select && item.selected)
        if(showFieldNameList.length > 0 && actionSelectItem) {
          actionSelectItem.toResponseFieldList = sortConnectorToFieldsByShowFieldNameList(actionSelectItem.toResponseFieldList, showFieldNameList)
        }
        
        const editOptions: ConnectorEditOptions = {
          ...result,
          appType: params?.isToThird ? AppTypeEnum.OutSide : AppTypeEnum.InSide,
        }
        
        this.detailValue = connectServerValueToComponentValueForEditWithTaskToPaas(editOptions)
        
        this.$nextTick(() => {
          this.userNameStyleOverlapPolyfill()
        })
        
      })
      
    },
    /**
    * @description 获取属性列表
    * @return {Record<string, any>} 属性列表
    */  
    getAttributes(): Record<string, any> {
      return {
        class: ConnectorModuleComponentNameEnum.ConnectorModuleCreateConnectorDetailDialog,
        props: {
          title: this.title,
          show: this.insideVisible,
          appendToBody: true
        },
        on: {
          'update:show': () => {
            this.hideDialog()
          },
          'closed': () => {
            this.onDialogCloseHandler()
          }
        },
      }
    },
    /** 
     * @description 获取 loading 加载指令属性
    */
    getLoadingAttributes(): Record<string, any> {
      return {
        directives: [
          {
            name: 'loading',
            value: this.fetchConnectorEditOptionsLoading
          }
        ]
      }
    },
    /** 
     * @description 弹窗显示事件
    */
    onVisibleShowHandler() {
      this.showDialog()
      this.fetchConnectorOptionsImpl()
    },
    /** 
     * @description 弹窗隐藏事件
    */
    onVisibleHideHandler() {
      this.hideDialog()
    },
    /** 
     * @description 值数据变化事件
    */
    onValueInputHandler(value: ConnectorDialogDetailData) {
      this.detailValue = value
    },
    /** 
     * @description 保存连接器配置实现
    */
    fetchSaveConnectorOptionsImpl(params: ConnectorSaveOptionsParams) {
      
      this.fetchSaveConnectorOptions(params)
        .then(() => {
          this.initConnectorDialogDefaultDetailValue()
          this.hideDialog()
          this.onDialogFinishHandler()
          
        })
        .catch(error => {
          Log.error(error, this.fetchSaveConnectorOptions.name)
        })
      
    },
    /**
     * @description 用户名样式重叠补丁
     */
    userNameStyleOverlapPolyfill() {
      
      const userInputList: HTMLInputElement[] = (this.$el.querySelectorAll('.user-search input') || []) as unknown as HTMLInputElement[]
      
      userInputList.forEach(userInputElement => {
        if (userInputElement.value) {
          userInputElement.value = ''
          userInputElement.placeholder = ''
        }
      })
      
    }
  },
  mounted() {
    //
  },
  render(h: CreateElement) {
    
    const attrs = this.getAttributes()
    const attrs_loading = this.getLoadingAttributes()
    
    return (
      <base-modal class={ConnectorModuleComponentNameEnum.ConnectorModuleEditConnectorDialog} {...attrs}>
        
        {this.insideVisible && (
          <ConnectorModuleConnectorDialogDetail 
            {...attrs_loading}
            value={this.detailValue}
            fromBizTypeName={this.fromBizTypeName}
            onInput={this.onValueInputHandler}
          />
        )}
        
        <div class="dialog-footer" slot="footer">
          
          <el-button
            disabled={this.disabled}
            onClick={this.cancel}
          >
            {t('common.base.cancel')}
          </el-button>
          
          <el-button 
            type="primary" 
            disabled={this.disabled}
            onClick={this.finish}
          >
            {t('common.base.finish')}
          </el-button>
          
        </div>
        
      </base-modal>
    )
  }
})
